<?php
declare (strict_types = 1);

namespace app\frontend\controller;

use app\frontend\model\Article;
use app\frontend\model\ArticleComment;
use app\frontend\model\ArticleContent;
use app\frontend\model\User;

class SendComment extends Base
{
    // 发出的评论列表
    public function index()
    {
        return view();
    }

    // 发出的评论列表数据接口
    public function list()
    {
        $userInfo = session('userInfo');
        $articleComment = ArticleComment::with(['articleTitle'])->where('user_id', $userInfo['id'])
            ->order('update_time', 'desc')
            ->select();
        if (!$articleComment->isEmpty()) {
            $count = ArticleComment::where('user_id', $userInfo['id'])
                ->count();
            $data = $articleComment->toArray();
        } else {
            $count = 0;
            $data = [];
        }

        $data = [
            'code' => 0,
            'msg' => '',
            'count' => $count,
            'data' => $data
        ];

        return json($data);
    }

    // 编辑评论页面
    public function edit()
    {
        $id = (int)input('get.id');

        $articleComment = ArticleComment::find($id);
        $article = Article::field('title, user_id')->find($articleComment->article_id);
        $author = User::field('nickname')->find($article->user_id);
        $articleContent = ArticleContent::field('content')
            ->where('article_id', $articleComment->article_id)
            ->find();

        return view('', [
            'articleComment' => $articleComment,
            'articleTitle' => $article->title,
            'articleContent' => $articleContent->content,
            'author' => $author->nickname
        ]);
    }

    // 编辑评论页面保存接口
    public function update()
    {
        $params['id'] = input('post.id');
        $params['comment'] = trim(input('post.comment'));

        ArticleComment::update([
            'content' => $params['comment'],
            'update_time' => time(),
            'id' => $params['id']
        ]);

        return json([
            'code' => 0,
            'msg' => '修改成功'
        ]);
    }

    // 删除评论
    public function delete()
    {
        $id = (int)trim(input('post.id', '', 'strip_tags'));

        ArticleComment::destroy($id);

        return json([
            'code' => 0,
            'msg' => '删除成功'
        ]);
    }

    // 我的评论多选删除接口
    public function deleteMulti()
    {
        $ids = input('post.ids', '', 'strip_tags');

        ArticleComment::destroy($ids);

        return json([
            'code' => 0,
            'msg' => '删除成功'
        ]);
    }
}
